package com.extremelylargepackage.editor;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.SAXException;

import com.extremelylargepackage.FileUtils;
import com.extremelylargepackage.GameActivity;
import com.extremelylargepackage.GameResources;
import com.extremelylargepackage.R;
import com.extremelylargepackage.entity.ScrollingBackground;
import com.extremelylargepackage.level.Level;
import com.extremelylargepackage.level.LevelParser;
import com.extremelylargepackage.level.MalformedLevelException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;

public class LevelEditorActivity extends ActivityForcePortrait
{
	
	private Level _level;
	private EditText _bgSpeed;
	private EditText _name;
	private static final int WAVE_EDIT_REQUEST = 0;
	private static final int LEVEL_LOAD_REQUEST = 1;
	
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.level_editor);
		findViewById(R.id.waves).setOnClickListener(new WavesHandler());
		findViewById(R.id.level_test_button).setOnClickListener(new TestLevelHandler());
		findViewById(R.id.save_level).setOnClickListener(new SaveHandler());
		_bgSpeed = (EditText) findViewById(R.id.bg_speed);
		_name = (EditText) findViewById(R.id.levelName);
		promptNewOrLoad();
	}
	
	private void editNewLevel()
	{
		_level = new Level();
		_level.setBackground(new ScrollingBackground(GameResources.getResource("space_nc")));
	}
	
	private void loadExistingLevel(String lName)
	{
		try {
			_level = LevelParser.parseLevel(FileUtils.CUSTOM_LEVEL_DIR + "/" + lName, true);
			_name.setText(lName);
			_bgSpeed.setText("" + _level.getBackground().getDirY());
			Toast.makeText(this, lName + " loaded successfully.", Toast.LENGTH_SHORT).show();
		} catch (Exception e) {
			new AlertDialog.Builder(this).setCancelable(false).setMessage("Failed to load - Level file corrupt.").setPositiveButton("Ok", null).show();
			e.printStackTrace();
		}
	}
	
	private void promptNewOrLoad()
	{
		new AlertDialog.Builder(this).setMessage("Create a new level or edit an existing level?")
		.setPositiveButton("Load Level", new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				Intent i = new Intent(LevelEditorActivity.this, LoadLevel.class);
				startActivityForResult(i, LEVEL_LOAD_REQUEST);
			}
		})
		.setNegativeButton("New Level", new DialogInterface.OnClickListener() 
		{
			@Override
			public void onClick(DialogInterface dialog, int which) 
			{
				editNewLevel();
			}
		})
		.setOnCancelListener(new DialogInterface.OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) 
			{
				finish();	
			}
		}).show();
	}
	
	private boolean saveLevel(File dir)
	{
		_level.getBackground().setDirY(Float.parseFloat(_bgSpeed.getText().toString()));
		_level.setName(_name.getText().toString());
		boolean success = true;
		try
		{	
			LevelWriter.saveLevel(_level, LevelEditorActivity.this, dir);
		}
		catch(IOException e)
		{
			success = false;
			new AlertDialog.Builder(this).setMessage(_level.getName() + " is not a valid file name. Please choose another name.").setPositiveButton("Ok", null).show();
		}
		return success;
	}
	
	@Override 
	public void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode)
		{
			case WAVE_EDIT_REQUEST:
				onWavesResult(resultCode, data);
				break;
			case LEVEL_LOAD_REQUEST:
				onLevelLoadResult(resultCode, data);
				break;
			default:
				break;
		}
	}
	
	private void onWavesResult(int resultCode, Intent data)
	{
		switch(resultCode)
		{
			case Activity.RESULT_OK:
				_level = (Level) data.getExtras().get("level");
				break;
			default:
				break;
		}
	}
	
	private void onLevelLoadResult(int resultCode, Intent data)
	{
		switch(resultCode)
		{
			case Activity.RESULT_OK:
				loadExistingLevel(data.getExtras().getString("name"));
				break;
			case Activity.RESULT_CANCELED:
				promptNewOrLoad();
				break;
			default:
				break;
		}
	}

	private class WavesHandler implements OnClickListener 
	{
		@Override
		public void onClick(View v) 
		{
			Intent intent = new Intent(LevelEditorActivity.this, WavesEditor.class);
			intent.putExtra("level", _level);
			startActivityForResult(intent, WAVE_EDIT_REQUEST);
		}
	}
	
	private class TestLevelHandler implements OnClickListener
	{
		@Override
		public void onClick(View v) 
		{
			saveLevel(null);
			Runtime.getRuntime().gc();
			Intent intent = new Intent(LevelEditorActivity.this, GameActivity.class);
			Bundle bundle = new Bundle();
			bundle.putString("level", FileUtils.TEST_LEVEL_NAME);
			bundle.putBoolean("local", true);
			intent.putExtras(bundle);
			startActivity(intent);
		}
	}
	
	private class SaveHandler implements OnClickListener
	{
		@Override
		public void onClick(View v) 
		{
			String name = _name.getText().toString();
			if(name == null || name.length() < 1)
			{
				new AlertDialog.Builder(LevelEditorActivity.this).setCancelable(false).setMessage("Save Failed - Level must have a name").setPositiveButton("Ok", null).show();
			}
			else if(FileUtils.customLevelExists(LevelEditorActivity.this, name))
			{
				new AlertDialog.Builder(LevelEditorActivity.this).setCancelable(false).setMessage("A level named \"" + name + "\" already exists. Overwrite?")
					.setPositiveButton("Yes", new DialogInterface.OnClickListener() 
					{
						@Override
						public void onClick(DialogInterface dialog, int which) 
						{
							doSave();
						}
					})
					.setNegativeButton("No", null).show();
			}
			else
			{
				doSave();
			}
			
		}
		
		public void doSave()
		{
			File levelsDir = FileUtils.getCustomLevelsDir(LevelEditorActivity.this);
			if(saveLevel(levelsDir))
				Toast.makeText(LevelEditorActivity.this, _level.getName() + " saved successfully.", Toast.LENGTH_SHORT).show();
		}
	}
}
